package com.edu.internship.util;

import com.alibaba.fastjson.JSONObject;
import com.edu.internship.glabal.constants.Constants;
import com.edu.internship.glabal.constants.ResultCodeEnum;
import com.edu.internship.glabal.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * code is far away from bug with the animal protecting
 *
 * @author v-lishiquan.gx@chinatelecom.cn
 * @description 附件的工具类
 * @date Create in 2020/2/26 11:10
 */
@Slf4j
public class AttachUtils {

    private AttachUtils() {
    }

    /**
     * 获取uuid的32位序列
     *
     * @return uuid
     */
    public static synchronized String createUuidSerial() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 下载附件
     *
     * @param inputStream 输入流
     * @param attachName  输出的文件名
     * @param response    响应
     */
    public static void download(InputStream inputStream, String attachName, HttpServletResponse response) {
        try (BufferedInputStream bis = IOUtils.buffer(inputStream);
             BufferedOutputStream bos = IOUtils.buffer(response.getOutputStream())) {
            String trueName = URLEncoder.encode(attachName, StandardCharsets.UTF_8.name());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + trueName);
            IOUtils.copy(bis, bos, Integer.parseInt(Constants.BaseCons.BUFFER_SIZE.getCode()));
        } catch (IOException e) {
            log.error("下载文件异常:[{}]", e.getMessage());
            throw new BusinessException(ResultCodeEnum.DOWNLOAD_FILE_ERROR);
        }
    }

    /**
     * 将文件保存到硬盘
     *
     * @param multipartFile 上传的文件
     * @param physicalFile  物理文件名
     */
    public static void saveToFile(MultipartFile multipartFile, String physicalFile) {
        try {
            File f = new File(physicalFile);
            if (!f.exists()) {
                f.getParentFile().mkdirs();
            }
            multipartFile.transferTo(f);
        } catch (IOException e) {
            log.error("上传文件异常:[{}]", e.getMessage());
            throw new BusinessException(ResultCodeEnum.UPLOAD_FILE_ERROR);
        }
    }

    /**
     * 上传文件并返回数据
     *
     * @param multipartFile 上传的文件
     * @param savePath      保存的空间
     * @param urlPrefix     url的前缀
     * @return 数据
     */
    public static JSONObject uploadAttach(MultipartFile multipartFile, String savePath, String fileSpace, String urlPrefix) {
        JSONObject result = new JSONObject(8);
        try {
            //获取文件后缀名
            String originalFileName = multipartFile.getOriginalFilename();
            if (Objects.isNull(originalFileName)) {
                return result;
            }
            String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
            //生成文件名
            String id = createUuidSerial();
            String fileName = id + suffix;
            fileSpace = Tools.isBlank(fileSpace) ? "" : fileSpace + "/";
            File saveFile = new File(savePath + fileSpace + fileName);
            FileUtils.forceMkdirParent(saveFile);
            //转存文件
            multipartFile.transferTo(saveFile.getAbsoluteFile());
            result.put("id", id);
            result.put("name", originalFileName);
            result.put("virtualName", fileName);
            result.put("url", urlPrefix + fileSpace + fileName);
            result.put("fileType", suffix.substring(1));
        } catch (IOException e) {
            log.error("上传文件异常:[{}]", e.getMessage());
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.UPLOAD_FILE_ERROR);
        }
        return result;
    }

    /**
     * 删除文件
     *
     * @param filePaths 文件路径集合
     * @param fileName  文件名
     */
    public static void deleteFile(List<String> filePaths, String fileName) {
        for (String filePath : filePaths) {
            boolean flag = FileUtils.deleteQuietly(new File(filePath + fileName));
            if (flag) {
                break;
            }
        }
    }
}
